import React, {Component} from "react";
import {connect} from "react-redux";
import lodash from "lodash";

// 组件
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import Banner from "@/views/viewCommon/Banner";

import {Toast, InputItem} from "antd-mobile";

import yhTools from "@tools/yh";
import "./wallet.scss";
import {InterfaceG} from "@config/Config";

import arrorwRight from "@images/paytool_right_icon.png";
import {
  setCouponListAction,
  setCouponAction
} from "@redux/Action/wallet/wallet";
import PaySkeleton from "@/component/skeleton/pay";
import {checkJumpPayResult} from "@tools/xhf";
import XhfPaying from "@component/XhfPaying";

/**
 * 描述：线上收银台
 * 作者：zenghq
 * 日期：2020-10-22
 */
@connect(
  state => ({
    selectedCoupon: state.walletReducer.selectedCoupon,
    mobile: state.getAppPlatformsDatas.mobile,
    extJsonStr: state.getAppPlatformsDatas.extJsonStr
  }),
  dispatch => ({
    setCouponListAction: value => dispatch(setCouponListAction(value)),
    setCouponAction: value => dispatch(setCouponAction(value))
  })
)
class wallet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isSmsPay: true, // 是否是短信支付
      isSmsCount: false, // 是否倒计时
      countDownTime: 60, // 倒计时时间
      isSetPwd: true, // 是否设置支付密码
      preOrderData: {
        transAmount: "--",
        quotaAmount: "--"
      }, // 预下单信息
      password: "", // 支付密码
      smsCode: "", // 短信验证码
      isClickedSend: true, // 是否点击过发送验证码
      status: "-1",
      bannerList: [],
      paytoolsData: {}
    };
    this.verifyToken = ""; // 短信验证码token
  }

  /*******************生命周期 start************************/
  async componentDidMount() {
    Toast.info(XhfPaying(), 100);
    this.getPayToolList();
  }

  componentWillUnmount = () => {
  };

  /*******************生命周期 end************************/

  /*******************业务方法 start************************/
  async initPreOrder(resPreOrder) {
    Toast.hide();
    const {code, data, message = ""} = resPreOrder;
    if (code === "0") {
      this.setState({
        preOrderData: data,
        status: 1
      });
      const {couponBoList = []} = data;
      this.props.setCouponListAction(couponBoList);
      this.props.setCouponAction(couponBoList[0]);
    } else {
      // 通知生活支付结果
      yhTools.noticePayFailed(message);
    }

    let isSetPwd = await this.checkSetPassword();
    if (isSetPwd) {
      this.setState({
        isSetPwd,
        isSmsPay: false
      });
    } else {
      this.setState({
        isSetPwd,
        isSmsPay: true
      });
    }
    this.getWalletBanner();
  }

  //获取banner
  async getWalletBanner() {
    let objs = {
      url: InterfaceG.walletBanner,
      params: {
        typeCode: "8"
      },
      _alertShow: false
    };
    let res = await yhTools.request(objs);
    if (res.code == "0") {
      this.setState({
        bannerList: res.data && res.data.length > 0 ? res.data : []
      });
    }
  }

  /** 检查是否设置支付密码 */
  async checkSetPassword() {
    let objs = {
      url: InterfaceG.checkSetPassword,
      params: {},
      _alertShow: false
    };
    let res = await yhTools.request(objs);
    if (res.code === "0") {
      return true;
    } else {
      return false;
    }
  }

  /**短信倒计时 */
  countDown() {
    let {countDownTime} = this.state;
    this.setState({
      isSmsCount: true,
      isClickedSend: false
    });
    this.sendTimer = setInterval(() => {
      if (countDownTime < 1) {
        clearInterval(this.sendTimer);
        this.sendTimer = null;
        this.setState({
          countDownTime: 60,
          isSmsCount: false
        });
      } else {
        countDownTime--;
        this.setState({
          countDownTime
        });
      }
    }, 1000);
  }

  /**短信支付发送短信 */
  sendVerifyCode() {
    const {preOrderData} = this.state;
    const objs = {
      url: InterfaceG.paySendVerifyCode,
      params: {
        mobilePhone: this.props.mobile,
        scene: preOrderData.outTradeNo
      }
    };
    return yhTools.request(objs);
  }

  /**确认支付 */
  confirmPay() {
    const {selectedCoupon = {}} = this.props;
    const {preOrderData, password, smsCode, isSmsPay} = this.state;
    const {query = {}} = this.props.location;
    if (!preOrderData) {
      // 通知生活支付结果
      yhTools.noticePayFailed("预下单失败，请重新发起");
      return;
    }
    if (isSmsPay && !this.checkSmsCode(smsCode)) {
      // 验证码登录校验失败
      return;
    }
    if (!isSmsPay && !this.checkPassword(password)) {
      // 密码登录校验失败
      return;
    }
    const objs = {
      url: InterfaceG.mmoney_password_confirm,
      params: {
        payTool: "1001",
        payScene: "IPAY",
        couponNo: selectedCoupon.no || "",
        outTradeNo: preOrderData.outTradeNo,
        tradeNo: preOrderData.tradeNo,
        verifyToken: this.verifyToken,
        password,
        smsCode,
        verifyType: isSmsPay ? "1" : "2" // 验密方式(1验证码(类型为验证码时smsCode不能为空) /2密码(类型为密码时password不能为空))
      }
    };
    const {successUrl, failUrl} = query;
    Toast.info(XhfPaying(), 100);
    yhTools.request(objs).then(res => {
      const {code, data, message = ""} = res;
      if (code === "0") {
        if (successUrl) {
          // 有成功页就去成功页
          this.props.history.push({
            pathname: successUrl,
            query: {
              payResult: data
            }
          });
          // 通知生活支付结果
          yhTools.noticePaySuccess("支付成功", false);
        } else {
          //判断是否进入支付结果页
          const {tradeNo} = preOrderData;
          checkJumpPayResult({
            tradeNo,
            history: this.props.history
          });
        }
      } else if (code === "11006") {
        Toast.info(message, 2);
      } else if (failUrl) {
        // 有成功页就去成功页
        this.props.history.push({
          pathname: failUrl,
          query: {
            payResult: res
          }
        });
        // 通知生活支付结果
        yhTools.noticePayFailed(message, false);
      } else {
        // 通知生活支付结果
        yhTools.noticePayFailed(message);
      }
    });
  }

  /**检测密码正确性 */
  checkPassword(password) {
    if (!password) {
      Toast.info("密码不能为空", 2);
      return false;
    }
    if (password.length != 6) {
      Toast.info("请输入六位支付密码", 2);
      return false;
    }
    return true;
  }

  /**检测验证码正确性 */
  checkSmsCode(smsCode) {
    const {isClickedSend} = this.state;

    if (isClickedSend) {
      Toast.info("请先获取短信验证码", 2);
      return false;
    }
    if (!smsCode) {
      Toast.info("验证码不能为空", 2);
      return false;
    }
    return true;
  }

  /**动态获取输入类型 */
  getInputType() {
    if (yhTools.platform() == "android") {
      return "number";
    }
    if (yhTools.platform() == "ios") {
      return "tel";
    }
  }

  /**取消支付 */
  cancelOrder() {
    yhTools.noticePayCanceled("取消支付");
  }

  /**获取支付方式 */
  getPayToolList = () => {
    let {extJsonStr} = this.props;
    let extJsonObj = {};
    if (extJsonStr) {
      extJsonStr = extJsonStr.replace(
        /(?:\s*['"]*)?([a-zA-Z0-9]+)(?:['"]*\s*)?:/g,
        '"$1":'
      );
      extJsonObj = JSON.parse(extJsonStr);
    }
    console.log(extJsonStr, extJsonObj);
    let lng = "",
      lat = "";
    if (extJsonObj.location) {
      lng = extJsonObj.location.lng;
      lat = extJsonObj.location.lat;
    }
    const objs = {
      url: InterfaceG.mmoney_pay_online_shenghuo_prepay_credit,
      params: {
        channel: "07",
        longitude: lng,
        latitude: lat,
        payScene: "IPAY"
      }
    };
    console.log('objs', objs)
    yhTools.request(objs).then(resp => {
      const {message, code, data = {}} = resp;
      if (code === "0") {
        this.setState({
          paytoolsData: data
        });

        this.initPreOrder(resp);
      } else {
        // 通知生活支付结果
        yhTools.noticePayFailed(message);
      }
    });
  };
  /*******************业务方法 end************************/

  /*******************点击事件 start************************/
  /**切换支付方式 */
  changePaytoolClick() {
    let {isSmsPay} = this.state;
    this.setState({
      isSmsPay: !isSmsPay
    });
  }

  /**点击确认支付 */
  confirmPayClick() {
    yhTools.debounceNew(this.confirmPay(), 200);
  }

  /**点击发送验证码 */
  async sendVerifyCodeClick() {
    const {mobile} = this.props;
    const {isSmsCount} = this.state;
    if (!mobile) {
      Toast.info("获取手机号失败", 2);
      return;
    }
    if (isSmsCount) {
      return;
    }
    let res = await this.sendVerifyCode();
    const {code, data} = res;
    if (code === "0") {
      this.verifyToken = data.verifyToken;
      this.countDown(60);
      Toast.info(
        `已向您手机${mobile.slice(0, 3)}****${mobile.slice(7, 11)}发送验证码`
      );
    } else {
      Toast.info(res.message, 2);
    }
  }

  /**密码输入改变 */
  inputChange(e) {
    let value = e.target.value;
    if (e.target.value.length > 6) {
      value = e.target.value.slice(0, 6);
    }
    this.setState(
      {
        password: value
      },
      () => {
        if (value.length === 6) {
          document.activeElement.blur();
        }
      }
    );
  }

  /**点击选券 */
  selectCouponClick() {
    this.props.history.push("/selectCouponForH5");
  }

  /**验证码输入 */
  smsCodeChange(v) {
    if (v && v.length === 6) {
      document.activeElement.blur();
    }
    this.setState({
      smsCode: v
    });
  }

  /*******************点击事件 end************************/

  /**渲染 */
  render() {
    const {
      isSetPwd,
      isSmsPay,
      isSmsCount,
      countDownTime,
      preOrderData,
      password,
      isClickedSend,
      status,
      bannerList
    } = this.state;
    const {selectedCoupon} = this.props;
    const _pageParams = {
      header: {
        title: "支付确认",
        // goToApp: true,
        goBackAction: () => {
          this.cancelOrder();
        }
      },
      componentDidRecover: () => {
        // 缓存
      },
      history: this.props.history,
      cacheLifecycles: this.props.cacheLifecycles
    };
    return (
      <MainLayout pageParams={_pageParams}>
        <PaySkeleton load={status === "-1"}>
          <div className="wallet-box">
            {/* 头部 */}
            <section className="wallet-top_content">
              <p className="shop-name">订单金额</p>
              <p className="unit">
                ¥<span className="pay-money">{preOrderData.transAmount}</span>
              </p>
            </section>
            {/* 详情 */}
            <section className="wallet-detail_content">
              <div className="wallet-detail-item">
                <div className="item-left">小辉付可用额度</div>
                <div className="item-right">
                  <div className="money">¥{preOrderData.quotaAmount}</div>
                </div>
              </div>

              <div className="wallet-detail-item">
                <div className="item-left">支付优惠</div>
                {selectedCoupon ? (
                  <div
                    onClick={this.selectCouponClick.bind(this)}
                    className="item-right red"
                  >
                    <div className="money">-¥{selectedCoupon.couponValue}</div>
                    <img src={arrorwRight} className="arrorw-img"/>
                  </div>
                ) : (
                  <div className="item-right">暂无</div>
                )}
              </div>
              <div
                className="wallet-detail-item"
                style={{borderBottomWidth: "0px"}}
              >
                <div className="item-left">支付活动</div>
                <div className="item-right red">随机减最高99元</div>
              </div>

              <div className="wallet-detail-item paytool-box">
                <div className="item-left">
                  {!isSmsPay ? "密码支付" : "验证码支付"}
                  {isSetPwd && (
                    <span
                      className="change-input"
                      onClick={this.changePaytoolClick.bind(this)}
                    >
											｜ 切换
                      {isSmsPay ? "密码支付" : "验证码支付"}
										</span>
                  )}
                </div>
              </div>
            </section>

            {!isSmsPay && (
              <section className="wallet-input-box">
                <div className="wallet-pwd_input-box">
                  <input
                    className="pwd-input"
                    value={password}
                    type={this.getInputType()}
                    pattern="[0-9]"
                    maxLength={6}
                    onChange={e => {
                      this.inputChange(e);
                    }}
                  />
                  {["", "", "", "", "", ""].map((item, index) => {
                    return password && password.split("")[index] ? (
                      <div key={index} className="input-item">
                        .
                      </div>
                    ) : (
                      <div key={index} className="input-item"></div>
                    );
                  })}
                </div>
              </section>
            )}
            {isSmsPay && (
              <section className="wallet-input-box">
                <div className="wallet-sms_input-box">
                  <InputItem
                    clear
                    placeholder="请输入验证码"
                    maxLength={6}
                    minLength={6}
                    pattern="[0-9]{6}"
                    type="tel"
                    className="sms-input"
                    onChange={this.smsCodeChange.bind(this)}
                    extra={
                      <div
                        className={isSmsCount ? "send-code send" : "send-code"}
                      >
                        {isClickedSend
                          ? "发送"
                          : isSmsCount
                            ? `重发${countDownTime}s`
                            : "重发"}
                      </div>
                    }
                    onExtraClick={lodash.throttle(
                      this.sendVerifyCodeClick.bind(this),
                      2000,
                      {trailing: false}
                    )}
                  ></InputItem>
                </div>
              </section>
            )}
            <Button
              style={{
                marginTop: "0.24rem",
                marginBottom: "0.7rem"
              }}
              onClick={this.confirmPayClick.bind(this)}
              buttonStyle={{
                height: "1rem",
                lineHeight: "1rem",
                borderRadius: "0.5rem"
              }}
            >
              确认支付
            </Button>
            {bannerList && bannerList.length > 0 && (
              <Banner bannerList={bannerList} history={this.props.history}/>
            )}
          </div>
        </PaySkeleton>
      </MainLayout>
    );
  }
}

export async function getServerSideProps({req,res,query}) {
  console.log('type of', typeof query.q)
  const queryQ = JSON.parse(query.q)
  console.log('queryQ',queryQ)
  for(let key in JSON.parse(queryQ)){
    console.log('key:', key)
    console.log('value:', JSON.parse(queryQ)[key])
  }
  // console.log('authHeaderStr',  queryQ.authHeaderStr)
  return {
    props: {props: {}}
  }
}

export default wallet;
